package org.luckystrophe.snowtoms.fragment;

import java.util.ArrayList;

import org.luckystrophe.snowtoms.R;
import org.luckystrophe.snowtoms.adapter.AdapterMessages;
import org.luckystrophe.snowtoms.model.CoachMarks;
import org.luckystrophe.snowtoms.model.impl.CoachMarksImpl;
import org.luckystrophe.snowtoms.model.impl.UserPost;
import org.luckystrophe.snowtoms.pref.AppPreference_;

import android.widget.ListView;

import com.actionbarsherlock.app.SherlockFragment;
import com.googlecode.androidannotations.annotations.AfterInject;
import com.googlecode.androidannotations.annotations.AfterViews;
import com.googlecode.androidannotations.annotations.Background;
import com.googlecode.androidannotations.annotations.Bean;
import com.googlecode.androidannotations.annotations.EFragment;
import com.googlecode.androidannotations.annotations.UiThread;
import com.googlecode.androidannotations.annotations.sharedpreferences.Pref;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

@EFragment(R.layout.fragment_sns)
public class SNSFragment extends SherlockFragment implements OnRefreshListener<ListView>, OnLastItemVisibleListener {

	@Bean
	AdapterMessages adapter;

	@Pref
	AppPreference_ appPref;

	@Bean(CoachMarksImpl.class)
	CoachMarks coachMarks;

	public PullToRefreshListView userPostList;

	private long startOffset = 0L;

	@Override
	public void onResume() {
		super.onResume();
	}

	@AfterInject
	public void afterInject() {
		coachMarks.showCoachMark(getSherlockActivity(), CoachMarks.COACH_MARK_2, appPref.isShowSNSFragment());
		getLists();
	}

	@AfterViews
	public void afterViews() {
		getSherlockActivity().getSupportActionBar().setTitle(R.string.actionbarTitleSNS);
		userPostList = (PullToRefreshListView) getView().findViewById(R.id.lv_userpost);
		userPostList.setAdapter(adapter);
		userPostList.setOnRefreshListener(this);
		userPostList.setOnLastItemVisibleListener(this);
		userPostList.setTranscriptMode(ListView.TRANSCRIPT_MODE_DISABLED);
	}

	@Override
	public void onRefresh(PullToRefreshBase<ListView> refreshView) {
		getLists();
	}

	@Background
	public void getLists() {
		afterGetMessages(AdapterMessages.LATEST_MESSAGES, adapter.getMessages(0L));
	}

	@Background
	public void addLists() {
		afterGetMessages(AdapterMessages.MORE_MESSAGES, adapter.getMessages(startOffset));
	}

	@UiThread
	public void afterGetMessages(int flag, ArrayList<UserPost> resultPosts) {
		startOffset = adapter.afterGetMessages(flag, resultPosts);
		if (flag == AdapterMessages.LATEST_MESSAGES) {
			userPostList.onRefreshComplete();
		}
	}

	@Override
	public void onLastItemVisible() {
		if (appPref.lastMsgId().get() == startOffset) {
			return;
		}
		addLists();
	}

}
